package com.lyh.hkcloud.module.m1300027;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.*;
import androidx.annotation.RequiresApi;
import com.lyh.hkcloud.R;
import com.lyh.hkcloud.adapter.ListViewListAdapter;
import com.lyh.hkcloud.base.BaseActivity;
import com.lyh.hkcloud.constants.BusinessConstants;
import com.lyh.hkcloud.constants.HttpUrlComstants;
import com.lyh.hkcloud.module.common.ActivityUtil;
import com.lyh.hkcloud.module.m1300027.adapter.ListViewAdapter;
import com.lyh.hkcloud.module.m1300027.service.Service;
import com.lyh.hkcloud.util.base.JsonUtil;
import com.lyh.hkcloud.util.base.SaveData;
import com.lyh.hkcloud.util.base.StringUtils;
import com.lyh.hkcloud.util.base.ToastUtils;
import com.lyh.hkcloud.util.http.listener.json.JsonFailuredListener;
import com.lyh.hkcloud.util.http.listener.json.JsonSuccessListener;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: zhongfan
 * @program: hkCloud
 * @description: 盘点资产信息
 * @company—date: 利元数据 2022-02-18 17:07
 **/
public class IndexActivity extends BaseActivity implements View.OnClickListener, ListViewAdapter.DeleteCallback {

    private ImageView goBack;
    private Button btReceiver;
    private Button btSave;
    private Button btInventoryCompleted;
    private LinearLayout llButton;
    private EditText etAssets;
    private Service service;

    private ListView lvAssets;
    private List<Map<String,Object>> dataMap = new ArrayList<>();
    private ListViewAdapter listViewAdapter;
    private Integer receiverFocusEvent = 0;
    List<String> assetIdList = new ArrayList<>();

    private Integer initialAssetsNum=0;

    /**
     * 上一个页面传过来的 盘点id和盘点状态
     */
    private JSONObject data;

    @Override
    protected Activity getActivity() {
        return this;
    }

    @Override
    protected int getSubmitResId() {
        return R.id.bt_receiver;
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_1300027;
    }

    @Override
    protected void onBeginInit() {
        service = new Service(IndexActivity.this);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void initView() {
        goBack = findViewById(R.id.go_back);
        lvAssets = findViewById(R.id.lv_assets);
        btReceiver = findViewById(R.id.bt_receiver);
        btSave = findViewById(R.id.bt_save);
        llButton = findViewById(R.id.ll_button);
        btInventoryCompleted = findViewById(R.id.bt_inventory_completed);
        etAssets= findViewById(R.id.et_assets);
        //获得焦点，并关闭软盘
        etAssets.setShowSoftInputOnFocus(false);
        goBack.setOnClickListener(this);
        btSave.setOnClickListener(this);
        btInventoryCompleted.setOnClickListener(this);
        getSupportActionBar().hide();

        //获取盘点列表页面的参数
        try {
            data = new JSONObject(getIntent().getStringExtra(BusinessConstants.DATA));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        listViewAdapter = new ListViewAdapter(this, dataMap, IndexActivity.this);
        listViewAdapter.setDeleteCallback(this);
        lvAssets.setAdapter(listViewAdapter);

        queryCountAssets();

        try {
            deleteButton(data.getString(BusinessConstants.INVENTORY_STATUS));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        registerReceiver(receiver, Filter());
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        unregisterReceiver(receiver);
    }

    private static IntentFilter Filter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BusinessConstants.ACTION);
        return intentFilter;
    }

    @Override
    protected void initEvent() {
        etAssets.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    if (BusinessConstants.SCAN_WHEN_ASSETS.equals(String.valueOf(etAssets.getText()))) {
                        etAssets.setText("");
                    }
                    receiverFocusEvent = 1;
                } else {
                    if (etAssets.getText() == null || "".equals(String.valueOf(etAssets.getText()))) {
                        etAssets.setText(BusinessConstants.SCAN_WHEN_ASSETS);
                    }
                    receiverFocusEvent = 0;
                }
            }
        });

        //回车事件，查询资产
        etAssets.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                //查询资产
                JSONObject jsonObject = new JSONObject();
                try {
                    String msg=etAssets.getText().toString().replace(BusinessConstants.SCAN_WHEN_ASSETS,"");
                    if (assetIdList.indexOf(msg) != -1) {
                        Toast.makeText(IndexActivity.this, "请不要重复扫描", Toast.LENGTH_SHORT).show();
                    }else if(StringUtils.isNotEmpty(msg)){
                        jsonObject.put("psncode", msg);
                        jsonObject.put("facardcode", msg);
                        queryAssets(jsonObject);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                etAssets.setText("");
                return true;
            }
        });
    }

    @Override
    protected void onSubmit() {

        //校验 是否扫描了资产
        if (dataMap.size() > initialAssetsNum) {
            ToastUtils.makeText(this, "请先暂存资产，然后执行盘点过账", ToastUtils.LENGTH_SHORT).show();
            return;
        }

        btReceiver.setEnabled(false);

        //先暂存资产
        SaveInventoryAssets();

//        this.inventoryVariance();
        Map<String, Object> inventoryAssetsMap = new HashMap<>();

        inventoryAssetsMap.put("dataIds",Arrays.asList(data.optString(BusinessConstants.ID)));
        inventoryAssetsMap.put("userid", SaveData.getString(this,"userid"));
        inventoryAssetsMap.put("username",  SaveData.getString(this,"userName"));
        try {
            inventoryAssetsMap.put(BusinessConstants.INVENTORY_ID,data.getString(BusinessConstants.INVENTORY_ID));
        } catch (JSONException e) {
            e.printStackTrace();
        }

        service.post(JsonUtil.toJSONObject(inventoryAssetsMap), HttpUrlComstants.INVENTORY_POSTING, new JsonSuccessListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {

            }
        }, new JsonFailuredListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {
                Log.e("error",response.optString("message"));
            }
        });
        try{
            //加休眠，不然报错
            Thread.sleep(1000);
        }
        catch (Exception e){
            Log.e("error",e.toString());
        }
        //返回盘点单列表
        Intent intent = new Intent(IndexActivity.this, com.lyh.hkcloud.module.m1300026.IndexActivity.class);
        IndexActivity.this.startActivity(intent);
    }


    /**
     * 暂存盘点资产
     * @author: zhongfan
     * @Date 2022/2/19 20:02
    **/
    private void SaveInventoryAssets(){
        List<String> facardidList = new ArrayList<>();
        List<Map<String, Object>> dataList = new ArrayList<>();

        if (dataMap == null || dataMap.size() == 0) {
            Toast.makeText(IndexActivity.this,"请先扫描资产",Toast.LENGTH_SHORT).show();
            return;
        }
        btSave.setEnabled(false);
        /*for(int i=0;i<lvAssets.getChildCount();i++){
            //取listview上所有的item中的指定控件
            EditText num=lvAssets.getChildAt(i).findViewById(R.id.et_num);
        }*/
        Map<String, Object> temporaryStorageMap = new HashMap<>();
        for (int i = 0; i < dataMap.size(); i++) {
            Map<String, Object> stringObjectHashMap = new HashMap<>();
            stringObjectHashMap.put("id",dataMap.get(i).get("facardid") == null ? "" : dataMap.get(i).get("facardid").toString());
            EditText et_num=lvAssets.getChildAt(i).findViewById(R.id.et_num);
            stringObjectHashMap.put("num",et_num.getText());
            stringObjectHashMap.put("linenum",i+1);

            dataList.add(stringObjectHashMap);
        }

        try {
            temporaryStorageMap.put("dataIds",data.optString(BusinessConstants.ID));
            temporaryStorageMap.put("data",dataList);
            temporaryStorageMap.put("userid", SaveData.getString(this,"userid"));
            temporaryStorageMap.put("username",  SaveData.getString(this,"userName"));
            temporaryStorageMap.put(BusinessConstants.INVENTORY_ID,data.getString(BusinessConstants.INVENTORY_ID));

        } catch (JSONException e) {
            e.printStackTrace();
        }

        service.post(JsonUtil.toJSONObject(temporaryStorageMap), HttpUrlComstants.TEMPORARY_INVENTORY, new JsonSuccessListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {
                Toast.makeText(IndexActivity.this,"保存成功",Toast.LENGTH_SHORT).show();
            }
        }, new JsonFailuredListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {
                Log.e("error",response.optString("message"));
            }
        });

        //返回
        Intent intent = new Intent(IndexActivity.this, com.lyh.hkcloud.module.m1300026.IndexActivity.class);
        IndexActivity.this.startActivity(intent);
    }

    /**
     * 扫描 接收者
     * @author: zhongfan
     * @Date 2022/2/15 21:00
     **/
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            String msg = intent.getStringExtra(BusinessConstants.TAG);

            if (assetIdList.indexOf(msg) != -1) {
                Toast.makeText(IndexActivity.this,"请不要重复扫描",Toast.LENGTH_SHORT).show();
                return;
            }

            Log.i(BusinessConstants.TAG, msg);
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("facardcode", msg);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            queryAssets(jsonObject);
        }

    };


    /**
     * 查询资产
     */
    private void queryAssets(JSONObject jsonObject) {
        Log.v("dataMap2:",dataMap.toString());
        for(int i=0;i<lvAssets.getChildCount();i++){
            //取listview上所有的item中的指定控件
            EditText num=lvAssets.getChildAt(i).findViewById(R.id.et_num);
            //替换数量
            dataMap.get(i).put("num",num.getText());
        }
        service.post(jsonObject, HttpUrlComstants.QUERY_ASSET_DETAILS, new JsonSuccessListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {

                try {

                    JSONObject jsonObject3 = JsonUtil.getJsonObject(response, "facardinfo", IndexActivity.this);
                    if (jsonObject3 == null) {
                        Toast.makeText(IndexActivity.this,"查询信息为空",Toast.LENGTH_SHORT);
                        return;
                    }

                    Map<String, Object> dataMam = new HashMap<>();

                    dataMam.put("facardcode",jsonObject3.get("facardcode") == null ? "" : jsonObject3.get("facardcode").toString());
                    dataMam.put("maname",jsonObject3.get("maname") == null ? "" : jsonObject3.get("maname").toString());
                    dataMam.put("manumber",jsonObject3.get("manumber") == null ? "" : jsonObject3.get("manumber").toString());
                    dataMam.put("facardid",jsonObject3.get("facardid") == null ? "" : jsonObject3.get("facardid").toString());
                    dataMam.put("num",jsonObject3.get("num") == null ? "" : jsonObject3.get("num").toString());

                    if (assetIdList.indexOf(dataMam.get("facardcode")) == -1) {
                        dataMap.add(dataMam);
                    }

                    assetIdList.add(jsonObject3.optString("facardcode"));

                    //盘点背景设置为空
                    lvAssets.setBackground(null);

                    //通知ListView更改数据源
                    if (listViewAdapter != null) {
                        listViewAdapter.notifyDataSetChanged();
                    } else {
                        listViewAdapter = new ListViewAdapter(IndexActivity.this, dataMap,IndexActivity.this);
                        lvAssets.setAdapter(listViewAdapter);
                    }
                    lvAssets.setSelection(dataMap.size() - 1);//设置显示列表的最后一项

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        }, new JsonFailuredListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {
                Log.e("error",response.optString("message"));
                ToastUtils.makeText(IndexActivity.this, msg, ToastUtils.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 通过盘点id查询资产信息
     * @return void
     * @author: zhongfan
     * @Date 2022/2/19 17:11
    **/
    public void queryCountAssets(){
        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put("dataid",data.optString(BusinessConstants.INVENTORY_ID));
            jsonObject.put("billtype",data.optString(BusinessConstants.BILL_TYPE));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        service.post(jsonObject, HttpUrlComstants.QUERY_COUNT_ASSETS_BY_INVENTORY_ID, new JsonSuccessListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {

                try {
                    JSONArray result = JsonUtil.getJsonObjectArray(response, "result", IndexActivity.this);
                    Boolean linestate=false;
                    if (result == null || result.length() == 0) {
                        Toast.makeText(IndexActivity.this, "获取数据为空", Toast.LENGTH_SHORT).show();
                        lvAssets.setBackgroundResource(R.drawable.toolbar_bg_selector);
                        return;
                    }

                    initialAssetsNum = result.length();
                    for (int i = 0; i < result.length(); i++) {
                        Map<String,Object> map =  new HashMap<>(3);
                        map.put("manumber",result.getJSONObject(i).get("manumber"));
                        map.put("id",result.getJSONObject(i).get("id"));
                        map.put("fatype",result.getJSONObject(i).get("fatype"));
                        map.put("facardcode",result.getJSONObject(i).get("facardcode"));
                        map.put("maname",result.getJSONObject(i).get("maname"));
                        map.put("num",result.getJSONObject(i).get("num"));
                        map.put("facardid",result.getJSONObject(i).get("facardid"));
                        map.put("linestate",result.getJSONObject(i).get("linestate"));
                        if(null!=result.getJSONObject(i).get("linestate")&&"已创建".equals(result.getJSONObject(i).getString("linestate"))) {
                            etAssets.setEnabled(true);
                        }
                        else {
                            etAssets.setEnabled(false);
                        }
                        dataMap.add(map);
                        assetIdList.add(result.getJSONObject(i).get("facardcode").toString());
                    }
                    //通知ListView更改数据源
                    if (listViewAdapter != null) {
                        listViewAdapter.notifyDataSetChanged();
                    } else {
                        listViewAdapter = new ListViewAdapter(IndexActivity.this, dataMap, IndexActivity.this);
                        lvAssets.setAdapter(listViewAdapter);
                    }
                    //lvAssets.setSelection(dataList.size() - 1);//设置显示列表的最后一项
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new JsonFailuredListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {
                Log.e("error",response.optString("message"));
            }
        });
    }

    /**
     * 根据盘点类型 删除按钮
     * @param inventoryStatus
     * @return void
     * @author: zhongfan
     * @Date 2022/2/21 17:52
    **/
    public void deleteButton(String inventoryStatus){
        if ("1".equals(inventoryStatus)) {
            llButton.removeView(btInventoryCompleted);
        }else if ("2".equals(inventoryStatus) || "3".equals(inventoryStatus)){
            llButton.removeView(btReceiver);
            llButton.removeView(btSave);
        }else{
            llButton.removeView(btReceiver);
            llButton.removeView(btSave);
            llButton.removeView(btInventoryCompleted);
        }
    }

    @Override
    public void deletePosition(int saveposition) {
        Log.v("saveposition:", String.valueOf(saveposition));
        for(int i=0;i<lvAssets.getChildCount();i++){
            //取listview上所有的item中的指定控件
            EditText num=lvAssets.getChildAt(i).findViewById(R.id.et_num);
            //替换数量
            dataMap.get(i).put("num",num.getText());
        }
        dataMap.remove(saveposition);
        assetIdList.remove(saveposition);
        listViewAdapter.setData(dataMap);
        listViewAdapter.notifyDataSetInvalidated();
    }


    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()){
            case R.id.go_back:
                intent = new Intent(IndexActivity.this, com.lyh.hkcloud.module.m1300026.IndexActivity.class);
                IndexActivity.this.startActivity(intent);
                break;
            case R.id.bt_save:
                SaveInventoryAssets();
                break;
            case R.id.bt_inventory_completed:
                intent = new Intent(IndexActivity.this, com.lyh.hkcloud.module.m1300028.IndexActivity.class);
                intent.putExtra(BusinessConstants.DATA,data.toString());
                // 使用activtiy的startActivityForResult方法跳转，第二参数是请求码，第二方数据回传时我们通过requestCode来判断是哪个页面
                IndexActivity.this.startActivityForResult(intent,BusinessConstants.requestCode);
                break;
        }
    }

    //时间分发方法重写
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        //如果是点击事件，获取点击的view，并判断是否要收起键盘
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            //获取目前得到焦点的view
            View v = getCurrentFocus();
            //判断是否要收起并进行处理
            if (ActivityUtil.isShouldHideKeyboard(v, ev)) {
                ActivityUtil.hideKeyboard(v.getWindowToken(), this, etAssets);
            }
        }
        //这个是activity的事件分发，一定要有，不然就不会有任何的点击事件了
        return super.dispatchTouchEvent(ev);
    }
}
